#include "mainwindow.h"

#include <string>
#include <QApplication>
#include <QSlider>
#include <QLabel>
#include <QObject>
#include <cstdlib>
using std::string;

string getColorString(int red, int green, int bule);

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.setStyleSheet(QString::fromUtf8("background-color: grey"));

    QLabel colorBoard(&w);
    colorBoard.setGeometry(w.width() / 2, w.height() / 10, w.width() * 2 / 5, w.height() * 4 / 5);
    colorBoard.setText(QString::fromUtf8("#000000"));
    colorBoard.setStyleSheet(QString::fromUtf8("background-color: black; color: white; font-size: 20px"));
    colorBoard.setAlignment(Qt::AlignCenter);

    QSlider *colorSilders[3] = {nullptr, nullptr, nullptr};
    for (auto &pSlider : colorSilders) {
        pSlider = new QSlider(Qt::Orientation::Horizontal, &w);
    }
    colorSilders[0]->setStyleSheet(QString::fromUtf8("background-color: red"));
    colorSilders[1]->setStyleSheet(QString::fromUtf8("background-color: green"));
    colorSilders[2]->setStyleSheet(QString::fromUtf8("background-color: blue"));

    auto fun = [&]() {
        int red = colorSilders[0]->value();
        int green = colorSilders[1]->value();
        int blue = colorSilders[2]->value();
        colorBoard.setStyleSheet(QString::fromStdString("background-color: " + getColorString(red, green, blue) +
                                                        ";color: " + getColorString(255 - red, 255 - green, 255 - blue) + ";font-size: 20px"));
        colorBoard.setText(QString::fromStdString(getColorString(red, green, blue)));
    };

    for (int i = 0; i < 3; ++i) {
        colorSilders[i]->setGeometry(w.width() / 10, w.height() * (2 * i + 1) / 7, w.width() / 3, w.height() / 7);
        colorSilders[i]->setMinimum(0);
        colorSilders[i]->setMaximum(255);
        QObject::connect(colorSilders[i], &QSlider::valueChanged, &colorBoard, fun);
    }


    w.show();
    int exitCode = a.exec();
    for (auto p : colorSilders) {
        delete p;
    }
    return exitCode;
}

string getColorString(int red, int green, int blue)
{
    string rtn = "#";
    int color = (red << 16) + (green << 8) + blue;
    char buffer[7];
    _itoa_s(color, buffer, 16);
    int leadingZero = 6 - strlen(buffer);
    rtn.insert(rtn.end(), leadingZero, '0');
    rtn += buffer;
    return rtn;
}